//
//  NSString+Ext.m
//  xuzhq
//
//  Created by xuzhq on 12-10-18.
//  Copyright (c) 2012年 xuzhq. All rights reserved.
//

#import "NSString+Ext.h"
//#import "NSData+Ext.h"
#import <CommonCrypto/CommonDigest.h>
#import "sys/utsname.h"
@implementation NSString (Ext)

+ (NSString *)deleteForeAndAftSpace:(NSString *)str
{
   return [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

- (NSString *)deleteSpecificString:(NSString *)str
{
  return  [self stringByReplacingOccurrencesOfString:str withString:@""];
}

- (NSString *)deleteSpecificStringWthSpace:(NSString *)str
{
    return  [self stringByReplacingOccurrencesOfString:str withString:@" "];
}

+ (NSString *)deleteSpacing:(NSString *)spacingStr
{
    //    spacingStr = [spacingStr stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    spacingStr = [spacingStr stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    spacingStr = [spacingStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    spacingStr = [spacingStr stringByReplacingOccurrencesOfString:@" " withString:@""];
    spacingStr = [spacingStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];//方法只是去掉左右两边的空格；
    return spacingStr;
}
+ (NSString *)deleteCardTextSpacing:(NSString *)spacingStr
{
    //    spacingStr = [spacingStr stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    spacingStr = [spacingStr stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    spacingStr = [spacingStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    spacingStr = [spacingStr stringByReplacingOccurrencesOfString:@" " withString:@""];

    spacingStr = [spacingStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];//方法只是去掉左右两边的空格；
    return spacingStr;
}



//得到中英文混合字符串长度 方法1

+ (NSInteger)convertToInt:(NSString*)strtemp
{
    NSInteger strlength = 0;
    char* p = (char*)[strtemp cStringUsingEncoding:NSUnicodeStringEncoding];
    for (int i=0 ; i<[strtemp lengthOfBytesUsingEncoding:NSUnicodeStringEncoding] ;i++) {
        if (*p) {
            p++;
            strlength++;
        }
        else {
            p++;
        }
        
    }
    return strlength;
}


//得到中英文混合字符串长度 方法2

+ (NSInteger)getToInt:(NSString*)strtemp

{
    NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    NSData* da = [strtemp dataUsingEncoding:enc];
    return [da length];
}
//该代码片段来自于: http://www.sharejs.com/codes/objectc/5447

+ (NSString*) doDevicePlatform
{
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *deviceString = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    
    if ([deviceString isEqualToString:@"iPhone1,1"])    return @"iPhone 1G";
    if ([deviceString isEqualToString:@"iPhone1,2"])    return @"iPhone 3G";
    if ([deviceString isEqualToString:@"iPhone2,1"])    return @"iPhone 3GS";
    if ([deviceString isEqualToString:@"iPhone3,1"]||[deviceString isEqualToString:@"iPhone3,2"]||[deviceString isEqualToString:@"iPhone3,3"])    return @"iPhone 4";
    if ([deviceString isEqualToString:@"iPhone4,1"])    return @"iPhone 4S";
    if ([deviceString isEqualToString:@"iPhone5,1"]||[deviceString isEqualToString:@"iPhone5,2"]||[deviceString isEqualToString:@"iPhone5,3"]||[deviceString isEqualToString:@"iPhone5,4"]||[deviceString isEqualToString:@"iPhone6,1"]||[deviceString isEqualToString:@"iPhone6,2"])    return @"iPhone 5";
    if ([deviceString isEqualToString:@"iPhone7,2"])    return
        @"iPhone 6";
    if ([deviceString isEqualToString:@"iPhone7,1"])    return
        @"iPhone 6Plus";
    if ([deviceString isEqualToString:@"iPhone3,2"])    return @"Verizon iPhone 4";
    if ([deviceString isEqualToString:@"iPod1,1"])      return @"iPod Touch 1G";
    if ([deviceString isEqualToString:@"iPod2,1"])      return @"iPod Touch 2G";
    if ([deviceString isEqualToString:@"iPod3,1"])      return @"iPod Touch 3G";
    if ([deviceString isEqualToString:@"iPod4,1"])      return @"iPhone 4S";
    if ([deviceString isEqualToString:@"iPod5,1"])      return @"iPhone 5";
    if ([deviceString isEqualToString:@"iPad1,1"])      return @"iPad";
    if ([deviceString isEqualToString:@"iPad2,1"])      return @"iPad 2 (WiFi)";
    if ([deviceString isEqualToString:@"iPad2,2"])      return @"iPad 2 (GSM)";
    if ([deviceString isEqualToString:@"iPad2,3"])      return @"iPad 2 (CDMA)";
    if ([deviceString isEqualToString:@"i386"])         return @"Simulator";
    if ([deviceString isEqualToString:@"x86_64"])       return @"Simulator";
    NSLog(@"NOTE: Unknown device type: %@", deviceString);
    return deviceString;
}




- (NSInteger) indexOf:(NSString *)text
{
    NSRange range = [self rangeOfString:text];
    if ( range.length > 0 ) {
        return range.location;
    } else {
        return -1;
    }
}

- (NSInteger) lastIndexOf:(NSString *)text
{
    NSRange range = [self rangeOfString:text options:NSBackwardsSearch];
    if ( range.length > 0 ) {
        return range.location;
    } else {
        return -1;
    }
}

- (BOOL) hasString:(NSString *)text
{
    NSUInteger idx = [self indexOf:text];
    return ((int)idx >= 0);
}

+ (NSString *)stringWithUrlEncodedString:(NSString *)string
{
    return [NSString stringWithUrlEncodedString:string encoding:kCFStringEncodingUTF8];
}

+ (NSString *)stringWithUrlEncodedString:(NSString *)string encoding:(CFStringEncoding)encoding
{
    CFStringRef refSource = CFBridgingRetain(string);
    CFStringRef refEsc = CFSTR(":/?#[]@!$ &'()*+,;=\"<>%{}|\\^~`");
    CFStringRef refDest = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, refSource, NULL, refEsc, encoding);
    CFRelease(refSource);
    
    NSString *rst = (NSString*)CFBridgingRelease(refDest);
    if (rst == nil) rst = @"";
	return rst;
}

- (NSString *)urlEncodedString
{
    return [self urlEncodedString:kCFStringEncodingUTF8];
}

- (NSString *)urlEncodedString:(CFStringEncoding)encoding
{
    return [NSString stringWithUrlEncodedString:self encoding:encoding];
}

+ (NSString *)stringWithUrlDecodedString:(NSString *)string
{
    return [NSString stringWithUrlDecodedString:string encoding:kCFStringEncodingUTF8];
}

+ (NSString *)stringWithUrlDecodedString:(NSString *)string encoding:(CFStringEncoding)encoding
{
    CFStringRef refSource = CFBridgingRetain(string);
    CFStringRef refDest = CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault, refSource, CFSTR(""), encoding);
    CFRelease(refSource);
    
    NSString *rst = (NSString*)CFBridgingRelease(refDest);
    if (rst == nil) rst = @"";
	return rst;
}

+ (CGFloat)calMaxWidthWithTitleArr:(NSArray <NSString *> *)titleArr titleHeight:(CGFloat)titleHeight rightMargin:(CGFloat)rightMargin
{
    CGFloat length = 0.0f;
    for (NSString *title in titleArr) {
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
        paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
        NSDictionary *attributes = @{NSFontAttributeName:xlFont(14), NSParagraphStyleAttributeName:paragraphStyle.copy};
        CGSize size = [title boundingRectWithSize:CGSizeMake(MAXFLOAT, titleHeight) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
        if (length < size.width) {
            length = size.width;
        }
    }
    return  length+rightMargin;
}


- (NSString*)urlDecodedString
{
    return [NSString stringWithUrlDecodedString:self encoding:kCFStringEncodingUTF8];
}

- (NSString*)urlDecodedString:(CFStringEncoding)encoding
{
    return [NSString stringWithUrlDecodedString:self encoding:encoding];
}

- (NSString *)hashStringBase64
{
    if (self.length <= 0) return @"";
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
    return [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
}

- (NSString *)md5:(NSString *)str
{
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result); // This is the md5 call
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}

- (NSString *)MD5String
{
    const char *cStr = [self UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result); // This is the md5 call
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}

-(NSMutableString *)stringWithSplit:(NSString *)sp push:(NSString *)push max:(NSInteger)max;
{
    NSMutableString *rst = [[NSMutableString alloc] init];
    
    //添加新信息
    [rst appendString:push];
    
    //现有线路
    int cnt = 1;
    if ([self length] > 0){
        NSArray *arr = [self componentsSeparatedByString:@","];
        for (NSString *str in arr) {
            if (![push isEqualToString:str]){
                [rst appendString:@","];    
                [rst appendString:str]; 
                cnt = cnt + 1;
                if (cnt >= max) break;
            }
        }
    }
    return rst;
}

- (BOOL)isPhoneNumber {
    NSString *regex = @"";
    switch (self.length) {
        case 7:
        {
            regex = @"^(13[0-9]|15[0-9]|18[0-9]|17[0-9]|14[0-9])\\d{4}$";
        }
            break;
        case 11:
        {
            regex = @"^(13[0-9]|15[0-9]|18[0-9]|14[0-9]|17[0-9])\\d{4,8}$";
        }
            break;
        default:
        {
            return NO;
        }
            break;
    }
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isValid = [predicate evaluateWithObject:self];
    return isValid;
}

@end

